import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:快速排序 优化版
 * User: 86183
 * Date: 2023-05-07
 * Time: 6:43
 */
public class sortDeom9 {
    public static void main(String[] args) {
        int[] a = {23,12,98,43,34,6,2,45,23,12,34,111,23};
        quickSort(a);
        System.out.println(Arrays.toString(a));
    }

    private static void quickSort(int[] a) {
        quick(a,0,a.length-1);
    }

    private static void quick(int[] a, int start, int end) {
        while (start >= end){
            return;
        }
        if(end - start + 1 <=6){
            insertSort(a,start,end);
            return;
        }
        int mid = findmidIndex(a,start,end);
        sortDeom5.swap(a,start,mid);
        int poviot = partition(a,start,end);
        quick(a,start,poviot-1);
        quick(a,poviot+1,end);

    }

    private static void insertSort(int[] a, int start, int end){
        for (int i = start+1;i <= end; i++) {
            int tmp = a[i];
            int j = i-1;
            for (;j >= start;j--) {
                if(a[j] > tmp){
                    a[j+1] = a[j];
                }else {
                    break;
                }
            }
            a[j+1] = tmp;
        }
    }

    private static int findmidIndex(int[] a, int start, int end) {
        int mid = (start+end)/2;
        if(a[start] > a[end]){
            if(a[start] < a[mid]){
                return start;
            }else if(a[end] > a[mid]){
                return end;
            }else {
                return mid;
            }
        }else {
            if(a[start] > a[mid]){
                return start;
            }else if(a[end] < a[mid]){
                return end;
            }else {
                return  mid;
            }
        }
    }

    private static int partition(int[] a, int start, int end) {
        int i = start;
        int poviot = a[start];
        while (start < end){
            while (start < end && a[end] >= poviot){
                end--;
            }
            a[start] = a[end];
            while (start < end && a[start] <= poviot){
                start++;
            }
            a[end] = a[start];
//            sortDeom5.swap(a,start,end);
        }
        a[start] = poviot;
//        sortDeom5.swap(a,i,start);
        return start;
    }
}
